package project.vip.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import project.order.weixi.WxUtils;
import project.order.work.AccessTokenThread;
import project.vip.po.Tpl;
import project.vip.po.TplData;

public class SendTplMsgUtils {

	protected static Log logger = LogFactory.getLog(DateUtils.class);

	/**
	 * 发送模板消息 appId 公众账号的唯一标识 appSecret 公众账号的密钥 openId 用户标识
	 */
	public static void sendCommonTpl(String openId, String tplId,
			LinkedHashMap<String, String> dataMap) {

		String access_token = AccessTokenThread.access_token;
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
				+ access_token;
		Tpl temp = new Tpl();
		temp.setUrl("http://weixin.qq.com/download");
		temp.setTouser(openId);
		temp.setTopcolor("#000000");
		temp.setTemplate_id(tplId);

		Map<String, TplData> m = new HashMap<String, TplData>();

		Iterator it = dataMap.entrySet().iterator();

		while (it.hasNext()) {

			Map.Entry entry = (Map.Entry) it.next();
			// 按顺序循环
			TplData data = new TplData();
			data.setColor("#000000");
			data.setValue(entry.getValue().toString());

			m.put(entry.getKey().toString().trim(), data);

		}

		temp.setData(m);
		String jsonString = JSONObject.fromObject(temp).toString();
		System.out.println("jsonString:" + jsonString);
		JSONObject jsonObject = WxUtils.httpRequest(url, "POST", jsonString);
		System.out.println(jsonObject);
		int result = 0;
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				System.err.println("发送消息模版[" + tplId + "]失败:"
						+ jsonObject.getInt("errcode") + "-"
						+ jsonObject.getString("errmsg"));
			}
		}
	}
}